import time
from datetime import datetime, timedelta

from flask import render_template, request, session, current_app, redirect, url_for, g, jsonify

from info import db
from info.constants import USER_COLLECTION_MAX_NEWS, QINIU_DOMIN_PREFIX
from info.models import User, News, Category
from info.modules.admin import admin_blu
from info.utils.common import user_login_data



# 后台登陆
from info.utils.img_storage import upload_img
from info.utils.response_code import RET, error_map


@admin_blu.route('/login',methods=["GET","POST"])
@user_login_data
def login():
    # 如果是get,查询身份免密码登陆
    if request.method == "GET":
        user = g.user.to_dict() if g.user else None
        user_id = session.get("user_id")
        is_admin = session.get("is_admin")

        if user_id and is_admin:
            return render_template("admin/index.html",user=user)

    username = request.form.get("username")
    password = request.form.get("password")

    if not all([username,password]):

        return render_template("admin/login.html",errmsg="")#用户名或密码错误

    # 查询是否有该管理员
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except BaseException as e:
        current_app.logger.error(e)
        return render_template("admin/login.html",errmsg="数据库查询错误")

    if not user:

        return render_template("admin/login.html",errmsg="用户不存在")
    # 比较密码

    if not user.check_password(password):

        return render_template("admin/login.html",errmsg="用户名/密码错误")

    # 状态保持
    session["user_id"] = user.id
    session["is_admin"] = True

    return redirect(url_for("admin.index"))


# 后台主页
@admin_blu.route('/index')
@user_login_data
def index():

    return render_template("admin/index.html",user=g.user.to_dict())


#退出
@admin_blu.route('/logout')
def logout():
    session.pop("user_id",None)
    session.pop("is_admin",None)

    return redirect("/")


#用户统计
@admin_blu.route('/user_count')
def user_count():

    total_count = 0
    # 查询总数
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 月新增

    mon_count = 0
    # 当月一号的日期字符串
    t = time.localtime()
    date_mon_str = "%d-%02d-01" % (t.tm_year,t.tm_mon)

    date_mon = datetime.strptime(date_mon_str,"%Y-%m-%d")
    try:
        mon_count = User.query.filter(User.is_admin==False,User.create_time > date_mon).count()
    except BaseException as e:
        current_app.logger.error(e)

    #日新增
    day_count = 0

    t = time.localtime()
    date_day_str = "%d-%02d-%02d" % (t.tm_year,t.tm_mon,t.tm_mday)

    date_day = datetime.strptime(date_day_str,"%Y-%m-%d")

    try:
        day_count = User.query.filter(User.is_admin==False,User.create_time > date_day).count()
    except BaseException as e:
        current_app.logger.error(e)

    #每天的登录量
    # 当天的时间,格式是字符串
    t = time.localtime()
    day_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    active_user = []
    active_time = []
    try:

        for i in range(0,31):
            #转换成可以比较的对象
            begin_date = datetime.strptime(day_str, "%Y-%m-%d") -timedelta(days=i)
            today_date = datetime.strptime(day_str, "%Y-%m-%d") + timedelta(days=1 - i)
            # 查询一天的用户最后登录时间,昨天零点到今天零点
            # oneday_count = User.query.filter(User.is_admin==False,begin_date <User.last_login <today_date).count()
            oneday_count = User.query.filter(User.is_admin==False,User.last_login>begin_date,
                                             User.last_login<today_date).count()
            active_user.append(oneday_count)
            active_time.append(begin_date.strftime("%Y-%m-%d"))

    except BaseException as e:
        current_app.logger.error(e)
    active_time.reverse()
    active_user.reverse()
    data = {
        "total_count":total_count,
        "mon_count":mon_count,
        "day_count":day_count,
        "active_user":active_user,
        "active_time":active_time
    }


    return render_template("admin/user_count.html",data=data)


#后台显示用户列表
@admin_blu.route('user_list')
def user_list():

    # 传过来的页数,默认第一页
    page = request.args.get("p", 1)
    # 转换
    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1

    user_list = []
    total_pages = 1
    try:
        # 查询出不是管理员的用户,按页分,每页十个
        pn = User.query.filter(User.is_admin==False).paginate(page, USER_COLLECTION_MAX_NEWS)
        user_list = [user.to_admin_dict() for user in pn.items]
        total_pages = pn.pages
    except BaseException as e:
        current_app.logger.error(e)

    data={
        "user_list":user_list,
        "cur_page":page,
        "total_page":total_pages
    }

    return render_template("admin/user_list.html",data=data)

#新闻审核
@admin_blu.route('news_review')
def news_review():

    # 传过来的页数,默认第一页
    page = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    # 转换
    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    total_pages = 1
    filt_list = [News.user_id != None]
    if keywords:
        filt_list.append(News.title.contains(keywords))
    try:
        # 查询出新闻,按页分,每页十个
        pn = News.query.filter(*filt_list).paginate(page, USER_COLLECTION_MAX_NEWS)
        news_list = [news.to_review_dict() for news in pn.items]
        total_pages = pn.pages
    except BaseException as e:
        current_app.logger.error(e)

    data={
        "news_list":news_list,
        "cur_page":page,
        "total_page":total_pages
    }

    return render_template("admin/news_review.html",data=data)

#审核详情
@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    # 查询该新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return render_template("admin/news_review_detail.html", data={"errmsg": "没有查询到指定的数据"})

    # 传到模板中
    return render_template("admin/news_review_detail.html", data={"news": news.to_dict()})


#提交审核
@admin_blu.route('/news_review_action', methods=['POST'])
def news_review_action():
    # 获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    # 通过或者拒绝
    if action not in ["accept","reject"]:
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    # 转换
    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    # 取新闻

    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not news:

        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])
    # 通过
    if action == "accept":

        news.status = 0
    else:
        news.status = -1
        # 拒绝理由
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
        news.reason = reason

    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])


#显示新闻版式
@admin_blu.route('news_edit')
def news_edit():

    # 传过来的页数,默认第一页
    page = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    # 转换
    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    total_pages = 1
    filt_list = [News.status !=1,News.status !=-1 ]
    if keywords:
        filt_list.append(News.title.contains(keywords))
    try:
        # 查询出新闻,按页分,每页十个
        pn = News.query.filter(*filt_list).paginate(page, USER_COLLECTION_MAX_NEWS)
        news_list = [news.to_review_dict() for news in pn.items]
        total_pages = pn.pages
    except BaseException as e:
        current_app.logger.error(e)

    data={
        "news_list":news_list,
        "cur_page":page,
        "total_page":total_pages
    }

    return render_template("admin/news_edit.html",data=data)


#修改新闻版式编辑
@admin_blu.route('news_edit_detail',methods=["GET","POST"])
def news_edit_detail():
    if request.method == "GET":
        # 获取参数
        news_id = request.args.get("news_id")
        try:
            news_id = int(news_id)
        except BaseException as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html",data={"errmsg":"参数错误"})
        # 查询新闻
        try:
            news = News.query.get(news_id)
        except BaseException as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", data={"errmsg": "数据查询失败"})

        if not news:
            return render_template("admin/news_edit_detail.html",data={"errmsg":"查询新闻不存在"})
        # 查询分类
        category_list = []
        try:
            categories = Category.query.all()
            for category in categories:

                category_dict = category.to_dict()
                is_selected = False
                if news.category_id == category.id:
                    is_selected = True
                category_dict["is_selected"] = is_selected
                category_list.append(category_dict)

        except BaseException as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", data={"errmsg": "数据查询失败"})
        if len(category_list):
            category_list.pop(0)

        return render_template("admin/news_edit_detail.html", data={"news":news.to_dict(),"categories":category_list})

    # 获取参数

    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    category_id = request.form.get("category_id")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    if not all([news_id,title,digest,category_id,content]):
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    # 转换类型
    try:
        news_id = int(news_id)
        category_id = int(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    # 查询
    try:
        news = News.query.get(news_id)
        category = Category.query.get(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])

    if not news and not category:
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])

    # 修改数据

    news.title = title
    news.category_id = category_id
    news.digest = digest
    if index_image:
        try:
            image_bytes = index_image.read()

            key = upload_img(image_bytes)
            news.index_image_url = QINIU_DOMIN_PREFIX + key
        except BaseException as e:
            return jsonify(errno=RET.THIRDERR,errmsg=error_map[RET.THIRDERR])

    news.content = content

    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])


#显示和修改新闻分类管理
@admin_blu.route('/news_type',methods=["GET","POST"])
def news_type():

    if request.method=="GET":

        categories = []
        try:
            categories = Category.query.all()
        except BaseException as e:
            current_app.logger.error(e)
            return render_template("admin/news_type.html", data={"errmsg":"查询失败"})
        if len(categories):
            categories.pop(0)

        return render_template("admin/news_type.html",data = categories)

    category_name = request.json.get("name")
    category_id = request.json.get("id")

    if not category_name:
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])


    if category_id:

        try:
            category_id = int(category_id)
        except BaseException as e:
            return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
        try:
            category = Category.query.get(category_id)
        except BaseException as e:
            return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])

        category.name = category_name

    else:
        c = Category()

        c.name = category_name
        db.session.add(c)

    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])












